import type { IColumnsOption } from 'vc';
import { type TableConfigProps } from 'vc/src/web';
import { CHECKBOX, INDEX, toF9, setHrefUrlTool } from '@/utils';
import { type GroupItemsParams, getGroupItems, type DeleteMemberParams, deleteMember } from './apis';
import { VcMessage } from 'vc';

export function useTable() {
  const loading = ref(false);

  const totalNum = ref(16);

  const tableData = ref<any[]>([]);

  const columns = ref<IColumnsOption[]>([
    { ...INDEX },
    {
      title: '发布日期',
      field: 'date',
      width: 150,
      align: 'center',
      sortable: true,
      sortBy: 'date',
      slots: {
        default: ({ row }) => {
          return formatDate(row.date);
        }
      }
    },
    {
      title: '标题',
      field: 'title',
      slots: {
        default: ({ row }) => {
          if (row.fileUrl || row.id) {
            return <a onClick={() => setHrefUrlTool(row.fileType, row.fileUrl, row.id || '', row.bizType || '')} v-html={row.title}></a>;
          } else {
            return row.title ? row.title : '-';
          }
        }
      }
    },
    {
      title: '相关机构',
      field: 'related',
      width: 300,
      slots: {
        default: ({ row }) => {
          if (row?.related?.length) {
            return <a onClick={() => toF9(row.related[0].id)} v-html={row.related[0].name}></a>;
          } else {
            return '-';
          }
        }
      }
    },
    {
      title: '类型',
      field: 'labels',
      width: 150,
      align: 'center',
      sortable: true,
      sortBy: 'labels',
      slots: {
        default: ({ row }) => {
          if (row?.labels?.length) {
            return row.labels.map((l) => l.name.replace('#', '')).join(', ');
          }
        }
      }
    },
    {
      title: '信息来源',
      field: 'source',
      width: 300,
      headerAlign: 'center',
      align: 'left'
    }
    // { ...INFO_SOURCE('source') }
  ]);

  return {
    loading,
    totalNum,
    tableData,
    columns
  };
}

export function useMemberTable(groupId: number) {
  const queryData = reactive<GroupItemsParams>({
    limit: 9999,
    offset: 0,
    sortType: 'desc',
    groupId,
    searchTxt: ''
  });

  const totalNum = ref(0);

  const tableData = ref([]);

  const loading = ref(false);

  const editFlag = ref(false);
  const getGroupTableData = async (groupId: number, isEdited = false) => {
    if (isEdited) {
      editFlag.value = true;
    }
    loading.value = true;
    const res = await getGroupItems(groupId, queryData);
    loading.value = false;
    totalNum.value = res.total;
    tableData.value = res.items;
  };

  const deleteGroupMember = async (companyId: string) => {
    const params: DeleteMemberParams = {
      groupId: queryData.groupId,
      ids: companyId
    };
    const res = await deleteMember(params);
    if (res.code === 200) {
      VcMessage.success('删除成功');
      getGroupTableData(queryData.groupId, true);
    } else {
      VcMessage.error('删除失败');
    }
  };

  const columns = ref<IColumnsOption[]>([
    { ...CHECKBOX },
    { ...INDEX },
    {
      field: 'name',
      title: '公司名称',
      fixed: 'left',
      align: 'left',
      slots: {
        default: ({ row }) => {
          return <a onClick={() => toF9(row.id)} v-html={row.name}></a>;
        }
      }
    },
    {
      title: '添加监控日期',
      field: 'monitorDate',
      width: 300,
      align: 'left',
      sortable: true,
      sortBy: 'monitorDate'
    },
    {
      title: '操作',
      width: 200,
      align: 'left',
      slots: {
        default: ({ row }) => {
          return <a onClick={() => deleteGroupMember(row.id)}>删除</a>;
        }
      }
    }
  ]);

  const tableConfig = reactive<TableConfigProps>({
    stripe: false,
    border: 'inner',
    size: 'mini'
  });

  const sortChange = (event: any) => {
    const { order } = event;
    queryData.sortType = order ? order : '';
    getGroupTableData(queryData.groupId);
  };

  return {
    queryData,
    totalNum,
    tableData,
    loading,
    editFlag,
    getGroupTableData,
    columns,
    tableConfig,
    sortChange
  };
}

export function useImportResultTable(groupName: string) {
  const columns = ref<IColumnsOption[]>([
    {
      title: '导入名称',
      field: 'companyName',
      align: 'left'
    },
    {
      title: '分组名称',
      align: 'left',
      slots: {
        default: () => {
          return groupName;
        }
      }
    },
    {
      title: '导入结果',
      align: 'left',
      width: 100,
      slots: {
        default: ({ row }) => {
          const result = { 0: '成功', 1: '失败' };
          return <span style={`color:${row.successOrFail === 0 ? '#008ef4' : '#ff5959'}`}>{result[row.successOrFail]}</span>;
        }
      }
    },
    {
      title: '失败原因',
      field: 'failReason',
      align: 'left'
    }
  ]);

  return {
    columns
  };
}

function formatDate(date) {
  if (date) {
    const _date = new Date(date);
    let Y = _date.getFullYear(),
      M: number | string = _date.getMonth() + 1,
      D: number | string = _date.getDate();
    M = M > 9 ? M : '0' + M;
    D = D > 9 ? D : '0' + D;
    return `${Y}-${M}-${D}`;
  } else {
    return '-';
  }
}
